//
//  ETONEHttpClient.m
//  YTwallet
//
//  Created by ZhangLin on 2019/3/14.
//  Copyright © 2019年 hadrlog. All rights reserved.
//

#import "ETONEHttpClient.h"
#import <AFNetworking.h>
#import "BaseViewController.h"
#import "LoginExpireViewController.h"
#import "PCCircleViewConst.h"

@implementation ETONEHttpClient

+(ETONEHttpClient*)sharedInstance{
    static ETONEHttpClient* httpClientInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        httpClientInstance = [[self alloc] init];
    });
    
    return httpClientInstance;
}
//有小菊花提示
- (void)doHTTPSPOST:(NSString *)requestUrlStr Parameters:(nullable NSDictionary*)dic HttpBody:(nullable NSData*)body SuccessHandler:(OnDoGETSuccessBlock)successHandler FailedHandler:(OnDoGETFailedBlock)failedHandler{
    //增加小菊花遮罩
    UIViewController *topVC = [self findCurrentViewController];
    dispatch_async(dispatch_get_main_queue(), ^{
        [(BaseViewController *)topVC showProgressTips:@"加载中" animated:YES];
    });
    
    
    
    NSURL *URL = [NSURL URLWithString:requestUrlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    [request setHTTPMethod:@"POST"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20;
    [manager.requestSerializer setValue:[AppTools getauthToken] forHTTPHeaderField:@"auth_token"];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/plain",@"text/html",nil];
 
    NSURLSessionDataTask *task = [manager POST:requestUrlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (NSString *key in [dic allKeys]) {
            
            [formData appendPartWithFormData:[[dic objectForKey:key] dataUsingEncoding:NSUTF8StringEncoding] name:key];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
        
        [self et_dealServerResponseObject:responseObject SuccessHandler:successHandler FailedHandler:failedHandler];
        
        //取消小菊花遮罩
        dispatch_async(dispatch_get_main_queue(), ^{
            [(BaseViewController *)topVC hideProgressTips:YES];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //取消小菊花遮罩
        dispatch_async(dispatch_get_main_queue(), ^{
            [(BaseViewController *)topVC hideProgressTips:YES];
            //提示message
            UIViewController *topVC = [self findCurrentViewController];
            [(BaseViewController *)topVC showFailedResultTips:error.localizedDescription animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        });
        
        failedHandler(error);
        
    }];
    [task resume];
}




//无小菊花提示
- (void)doHTTPSPOSTNOTips:(NSString *)requestUrlStr Parameters:(nullable NSDictionary*)dic HttpBody:(nullable NSData*)body SuccessHandler:(OnDoGETSuccessBlock)successHandler FailedHandler:(OnDoGETFailedBlock)failedHandler{

    NSURL *URL = [NSURL URLWithString:requestUrlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    [request setHTTPMethod:@"POST"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 60;
    [manager.requestSerializer setValue:[AppTools getauthToken] forHTTPHeaderField:@"auth_token"];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/plain",@"text/html",nil];
    
    NSURLSessionDataTask *task = [manager POST:requestUrlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (NSString *key in [dic allKeys]) {
            
            [formData appendPartWithFormData:[[dic objectForKey:key] dataUsingEncoding:NSUTF8StringEncoding] name:key];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);

        
        [self etNOtips_dealServerResponseObject:responseObject SuccessHandler:successHandler FailedHandler:failedHandler];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  
        failedHandler(error);
        
    }];
    [task resume];
}



// 无小菊花处理网络正常数据
-(void)etNOtips_dealServerResponseObject:(id)responseObject
                    SuccessHandler:(OnDoGETSuccessBlock)successHanlder
                     FailedHandler:(OnDoGETFailedBlock)failedHandler{
    
    //如果code不等于0000 提示错误信息  否则返回正常数据
    NSDictionary *dic = [responseObject mj_JSONObject];
    NSString *code = dic[@"code"];
    successHanlder(responseObject);
    
    //如果code等于I0002  退出登录
    if ([@"I0002" isEqualToString:code]) {
        UIViewController *topVC = [self findCurrentViewController];
        LoginExpireViewController *loginExpireVC = [[LoginExpireViewController alloc] init];
        [topVC presentViewController:loginExpireVC animated:YES completion:nil];
        //清除指纹和手势
        
        [PCCircleViewConst saveGesture:nil Key:gestureFinalSaveKey];
        [PCCircleViewConst saveFingerprint:nil Key:fingerprintStatueKey];
        
        
        NSLog(@"登录已失效");
    }
    
    //不展示错误信息
    /*
    if (![@"0000" isEqualToString:code]) {
        //提示message
        UIViewController *topVC = [self findCurrentViewController];
        [(BaseViewController *)topVC showFailedResultTips:dic[@"msg"] animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        //code不是0000   失败返回
        return;
    }
     */
}






// 有小菊花处理网络正常数据
-(void)et_dealServerResponseObject:(id)responseObject
                    SuccessHandler:(OnDoGETSuccessBlock)successHanlder
                     FailedHandler:(OnDoGETFailedBlock)failedHandler{
    
    //如果code不等于0000 提示错误信息  否则返回正常数据
    NSDictionary *dic = [responseObject mj_JSONObject];
    NSString *code = dic[@"code"];
    successHanlder(responseObject);
    
    //如果code等于I0002  退出登录
    if ([@"I0002" isEqualToString:code]) {
        UIViewController *topVC = [self findCurrentViewController];
        LoginExpireViewController *loginExpireVC = [[LoginExpireViewController alloc] init];
        [topVC presentViewController:loginExpireVC animated:YES completion:nil];
        NSLog(@"登录已失效");
        
        //清除指纹和手势
        
        [PCCircleViewConst saveGesture:nil Key:gestureFinalSaveKey];
        [PCCircleViewConst saveFingerprint:nil Key:fingerprintStatueKey];
    }
    
    if (![@"0000" isEqualToString:code]) {
        //提示message
        UIViewController *topVC = [self findCurrentViewController];
        [(BaseViewController *)topVC showFailedResultTips:dic[@"msg"] animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        //code不是0000   失败返回
        return;
    }
}

- (UIViewController *)findCurrentViewController
{
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    UIViewController *topViewController = [window rootViewController];
    
    while (true) {
        
        if (topViewController.presentedViewController) {
            
            topViewController = topViewController.presentedViewController;
            
        } else if ([topViewController isKindOfClass:[UINavigationController class]] && [(UINavigationController*)topViewController topViewController]) {
            
            topViewController = [(UINavigationController *)topViewController topViewController];
            
        } else if ([topViewController isKindOfClass:[UITabBarController class]]) {
            
            UITabBarController *tab = (UITabBarController *)topViewController;
            topViewController = tab.selectedViewController;
            
        } else {
            break;
        }
    }
    return topViewController;
}
//下载文件
-(void)downloadDocFromUrl:(NSString*)path  Storefile:(NSString *)file finish:(OnDocFinish)finish{
    AFHTTPSessionManager *session=[AFHTTPSessionManager manager];
    
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:path]];
    
   NSURLSessionDownloadTask *task=[session downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        finish(false);
        //下载进度
       NSLog(@"%@",downloadProgress);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
          finish(false);
        //下载到哪个文件夹
        return [NSURL fileURLWithPath:file];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        finish(true);
        //下载完成了
        NSLog(@"下载完成了 %@",filePath);
    }];
    [task resume];
}

@end
